#!/bin/bash
#-------------------------------------------------------------
# Author: zhangxu
# Date: 2021-09-24
# Desc: Deploy Jenkins
#-------------------------------------------------------------

checkJenkinsEnv(){
  # check user for nexus
  if id -u jenkins > /dev/null 2>&1;then
    echo "user jenkins is exist"
  else
    echo "user jenkins does not exist, start creating nexus user."
    sleep 1
    useradd jenkins
    echo "jenkins user is ready"
  fi

  # check java environments
  which java
  if [ $? -eq 0 ];then
    echo "java environments is ready"
  else
    yum -y install java-1.8.0-openjdk
  fi

  # check for ulimit

  if [ `su jenkins -c 'ulimit -n'` -lt 65535 ];then
    cat >>/etc/security/limits.conf <<EOF
    jenkins soft nofile 100001
    jenkins hard nofile 100002
EOF
  else
    echo "ulimit is `su nexus -c 'ulimit -n'`"
  fi
}

preDeployJenkins(){
  # set JENKINS_HOME
  echo 'export JENKINS_HOME=/opt/jenkinsHome' >> /etc/profile
  source /etc/profile
  mkdir -p $JENKINS_HOME
  chown -R jenkins.jenkins $JENKINS_HOME

  # download jenkins
  curl -s -o /home/jenkins/jenkins.war  https://mirrors.tuna.tsinghua.edu.cn/jenkins/war-stable/latest/jenkins.war
  chown jenkins.jenkins /home/jenkins/jenkins.war

  # prepare script for jenkins
cat >>/home/jenkins/start.sh<<EOF
#!/bin/bash
source /etc/profile
nohup java -Dhudson.security.csrf.GlobalCrumbIssuerConfiguration.DISABLE_CSRF_PROTECTION=true -Duser.timezone=Asia/Shanghai -jar jenkins.war --httpPort=8080 >/home/jenkins/temp.txt &
EOF

chmod +x /home/jenkins/start.sh
chown jenkins.jenkins /home/jenkins/start.sh
}

startJenkins(){
  su - jenkins -c "bash /home/jenkins/start.sh"
}

main(){
  checkJenkinsEnv
  preDeployJenkins
  startJenkins
}

main